package com.yf.catcafe.controller;

import com.yf.catcafe.pojo.dto.UserInfoDto;
import com.yf.catcafe.pojo.dto.UserLoginDto;
import com.yf.catcafe.pojo.dto.UserRegisterDto;
import com.yf.catcafe.pojo.enity.User;
import com.yf.catcafe.pojo.vo.UserInfoVo;
import com.yf.catcafe.pojo.vo.UserLoginVo;
import com.yf.catcafe.result.Result;
import com.yf.catcafe.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/catcafe")
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    private UserService userService;

    private static final String UPLOAD_DIR = "D:/UserUploads/";

    @PostMapping("/login")
    public Result<UserLoginVo> login(@RequestBody UserLoginDto  userLoginDto){
        System.out.println("到达请求");
        User user=userService.login(userLoginDto);
        UserLoginVo userLoginVo=new UserLoginVo();
        userLoginVo.setUsername(user.getUsername());
        userLoginVo.setRole(user.getRole());
        userLoginVo.setId(user.getId());
        return Result.success(userLoginVo);
    }

    @GetMapping("/user/profile")
    public Result<UserInfoVo> get(@RequestParam(value = "username") String username){
        User user=userService.get(username);
        UserInfoVo userInfoVo=new UserInfoVo();
        userInfoVo.setImage(user.getImage());
        userInfoVo.setRole(user.getRole());
        userInfoVo.setPhone(user.getPhone());
        userInfoVo.setNickname(user.getNickName());
        userInfoVo.setUsername(username);
        return Result.success(userInfoVo);
    }

    @PostMapping("/user/update")
    public Result updateUser(
            @RequestParam("nickname") String nickname,
            @RequestParam("phone") String phone,
            @RequestParam("username") String username,
            @RequestParam(value = "avatar", required = false) MultipartFile image) throws IOException {

        // 保存图片到服务器
        String fileName = UUID.randomUUID() + "_" + image.getOriginalFilename();
        Path filePath = Paths.get(UPLOAD_DIR + fileName);
        image.transferTo(filePath);

        UserInfoDto userInfoDto=new UserInfoDto();
        userInfoDto.setNickname(nickname);
        userInfoDto.setPhone(phone);
        userInfoDto.setImage("/uploads/"+fileName);
        userInfoDto.setUsername(username);
        userService.update(userInfoDto);
        return Result.success();
    }

    @PostMapping("/register")
    public Result register(@RequestBody UserRegisterDto userRegisterDto){
        userService.register(userRegisterDto);
        return Result.success();
    }

}
